package com.wrb.pwd.service;

import com.alibaba.fastjson.JSONArray;
import com.wrb.pwd.constant.Constant;
import com.wrb.pwd.model.User;
import com.wrb.pwd.utils.MD5Utils;
import com.wrb.pwd.utils.PageUtils;
import com.wrb.pwd.utils.SecurityAES;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author wrb
 * @date 2019/9/16 13:59
 */
public class UserService {

	private static List<User> userList;

	public static List<User> getUserList() {
		return userList;
	}

	static {
		userList = readJsonFile();
	}

	private UserService() {
	}

	public static UserService getInstance() {
		return Inner.INSTANCE;
	}

	private static class Inner {
		private static final UserService INSTANCE = new UserService();
	}

	/**
	 * 查看用户密码列表
	 *
	 * @return
	 */
	public PageUtils getUserList(String platform, int pageNo, int pageSize) {
		List<User> filterList = userList;
		if (platform != null && !"".equals(platform.trim())) {
			filterList = userList.stream().filter(p -> p.getPlatform() != null && p.getPlatform().contains(platform)).collect(Collectors.toList());
		}
		return PageUtils.startPage(pageNo, pageSize, filterList);
	}

	/**
	 * 新增一个用户信息
	 *
	 * @param user
	 * @return
	 */
	public boolean insertUser(User user) {
		try {
			userList.add(user);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 更新一个用户信息
	 *
	 * @param user
	 * @return
	 */
	public boolean updateUser(User user) {
		try {
			for (User filterUser : userList) {
				if (filterUser.getId().equals(user.getId())) {
					if (user.getName() != null && !"".equals(user.getName().trim())) {
						filterUser.setName(user.getName());
					}
					if (user.getEmail() != null && !"".equals(user.getEmail().trim())) {
						filterUser.setEmail(user.getEmail());
					}
					if (user.getPhone() != null && !"".equals(user.getPhone().trim())) {
						filterUser.setPhone(user.getPhone());
					}
					if (user.getAuxiliaryEmail() != null && !"".equals(user.getAuxiliaryEmail().trim())) {
						filterUser.setAuxiliaryEmail(user.getAuxiliaryEmail());
					}
					if (user.getUpdateTime() != null) {
						filterUser.setUpdateTime(user.getUpdateTime());
					}
					if (user.getRemark() != null && !"".equals(user.getRemark().trim())) {
						filterUser.setRemark(user.getRemark());
					}
					if (user.getUserSalt() != null) {
						filterUser.setUserSalt(user.getUserSalt());
					}
					if (user.getPassword() != null && !"".equals(user.getPassword())) {
						filterUser.setPassword(user.getPassword());
					}
					break;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 通过 id 删除 user
	 *
	 * @param id
	 * @return
	 */
	public boolean deleteUser(String id) {
		try {
			userList = userList.stream().filter(p -> !id.equals(p.getId())).collect(Collectors.toList());
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 通过 id 获取 user
	 *
	 * @param id
	 * @return
	 */
	public User getUser(String id) {
		for (User user : userList) {
			if (user.getId().equals(id)) {
				return user;
			}
		}
		return null;
	}

	private static List<User> readJsonFile() {
		StringBuilder jsonStrs = new StringBuilder();
		BufferedReader reader = null;
		InputStream in = null;
		try {
			in = UserService.class.getResourceAsStream("/" + Constant.DATA_FILE_NAME);
			InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempStr = null;
			while ((tempStr = reader.readLine()) != null) {
				jsonStrs.append(tempStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("处理json文件流错误");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误1");
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误2");
				}
			}
		}
		String decrypt = jsonStrs.toString();
		if (!"".contentEquals(jsonStrs)) {
			// AES解密
			decrypt = SecurityAES.decrypt(jsonStrs.toString().trim());
		}

		assert decrypt != null;
		List<User> userList = JSONArray.parseArray(decrypt.trim(), User.class);
		if (userList == null || userList.isEmpty()) {
			userList = new ArrayList<>();
		}
		return userList;
	}

	public String generatePassword(String platformStr, String userSalt) {
		String password = MD5Utils.md5(platformStr + MD5Utils.salt + userSalt);
		String pwdStr = password.substring(0, 15);
		boolean isEdit = false;
		for (int i = 0; i < pwdStr.length(); i++) {
			//获取当前char字符
			char c = pwdStr.charAt(i);
			//如果是大写
			if (Character.isUpperCase(c)) {
				//把大写改为小写
				pwdStr = pwdStr.replaceFirst(String.valueOf(c), (char) (c + 32) + "!");
				isEdit = true;
				break;
			}
		}
		if (!isEdit) {
			int rank = new Random(platformStr.charAt(0)).nextInt(10) + 1;
			StringBuilder sb = new StringBuilder(pwdStr);
			int c = 'a' + new Random(rank).nextInt(26);
			sb.replace(rank, rank + 1, (char) c + "!");
			pwdStr = sb.toString();
		}
		return pwdStr;
	}

}
